<?php

namespace addons\groupon\listener\order;

use addons\groupon\exception\Exception;
use addons\groupon\model\Cart;
use addons\groupon\model\Config;
use addons\groupon\model\Order;
use addons\groupon\model\Store;
use addons\groupon\model\User;

/**
 * 支付成功
 */
class Payed
{

    // 订单支付成功
    public function GrouponOrderPayedAfter(&$params) {
        // 订单支付成功
        $order = $params['order'];

        // 重新查询订单
        $order = Order::with('item')->where('id', $order['id'])->find();
        $items = $order ? $order['item'] : [];

        $this->sendNewOrderNotification($order);
    }


    // 发送自提点新订单通知
    public function sendNewOrderNotification($order) {
        $data = [];
        if ($order['store_id']) {
            // 存在自提点，查询自提点管理员
            $store = Store::with(['userStore.user'])->where('id', $order['store_id'])->find();

            $userStoreList = $store['user_store'] ? : [];
            unset($store['user_store']);

            // 当前自提点所有用户管理员
            $userList = [];
            foreach ($userStoreList as $user) {
                if ($user['user']) {
                    $userList[] = $user['user'];
                }
            }

            // 有用户才能发送消息
            if ($userList) {
                $data[] = [
                    'store' => $store,
                    'userList' => $userList
                ];
            }
        }
        // 存在要通知的自提点管理员
        if ($data) {
            // 按自提点为单位发送通知
            foreach ($data as $key => $sendData) {
                \addons\groupon\library\notify\Notify::send(
                    $sendData['userList'],
                    new \addons\groupon\notifications\store\Order([
                        'store' => $store,
                        'order' => $order,
                        'event' => 'store_order_new'
                    ])
                );
            }
        }
    }
}
